package com.tf_cut.admin.platform.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.tf_cut.admin.annotation.Decrypt;
import com.tf_cut.admin.annotation.Encrypt;
import com.tf_cut.admin.backend.api.BackEndApi;
import com.tf_cut.admin.common.pojo.PageInfo;
import com.tf_cut.admin.common.pojo.Result;
import com.tf_cut.admin.person.vo.PersonAndAccountVo;
import com.tf_cut.admin.platform.excel.GrantPersonExcel;
import com.tf_cut.admin.platform.excel.SellerOrderExcel;
import com.tf_cut.admin.platform.vo.GrantDetailVo;
import com.tf_cut.admin.platform.vo.GrantVo;
import com.tf_cut.admin.platform.vo.OrderDetailVO;
import com.tf_cut.admin.platform.vo.PersonalTaxVo;
import com.tf_cut.admin.platform.vo.SetHistoryVo;
import com.tf_cut.admin.seller.vo.SellerBillAndConsigneeVo;
import com.tf_cut.admin.seller.vo.SellerOrderVo;
import com.tf_cut.admin.util.ExcelUtils;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/platform/grant")
@Slf4j
public class GrantController {
	private static final String FILE_NAME = "order";

	private static final String FILE_GRENTNAME = "申请记录";
	@Autowired
	private BackEndApi platformGrantApi;

	@Value("${mobile.upload.path}")
	private String filePath;

	private String uploadPath = "mobile/upload/";

	@GetMapping("list")
	public ModelAndView sellerList() {
		return new ModelAndView("platform/grant/list", "platformGrant", null);
	}
	
	
	@GetMapping("listbh")
	public ModelAndView sellerListbh() {
		return new ModelAndView("platform/grant/listbh", "platformGrant", null);
	}

	@GetMapping("query")
	public ModelAndView sellerQueryList() {
		return new ModelAndView("platform/grant/query", "platformQueryGrant", null);
	}

	@GetMapping("sethistory")
	public ModelAndView sethistory() {
		return new ModelAndView("platform/grant/sethistory", "platformQueryGrant", null);
	}

	@GetMapping("inthistory")
	public ModelAndView inthistory() {
		return new ModelAndView("platform/grant/inthistory", "platformQueryGrant", null);
	}

	@GetMapping("setup")
	public ModelAndView sellersetupList(HttpServletRequest request) {
		String tax = (String) request.getSession().getAttribute("tax");
		if (tax == null || tax.equals("")) {
			tax = "3";
		}
		return new ModelAndView("platform/grant/setup", "tax", tax);
	}

	// 进入关联页面
	@GetMapping("setupinsert")
	public ModelAndView refInsert() {
		return new ModelAndView("platform/grant/setupinsert", "service", null);
	}

	@GetMapping(value = "queryByNames")
	public Result<List<OrderDetailVO>> queryByNames(@RequestParam("time") String time, HttpServletRequest request) {
		String tax = (String) request.getSession().getAttribute("tax");
		if (tax == null || tax.equals("")) {
			tax = "3";
		}
		List<OrderDetailVO> list = platformGrantApi.queryByNames(time, tax);
		return Result.of(list);
	}

	@GetMapping(value = "queryByName")
	public Result<List<PersonalTaxVo>> queryByName(@RequestParam("payeeName") String payeeName,
			@RequestParam("serviceName") String serviceName, @RequestParam("time") String[] time,
			@RequestParam("cardCode") String cardCode, @RequestParam("startaxAmount") String startaxAmount,
			@RequestParam("endtaxAmount") String endtaxAmount, @RequestParam("startaxMoney") String startaxMoney,
			@RequestParam("endtaxMoney") String endtaxMoney) {
		List<PersonalTaxVo> list = platformGrantApi.queryByName(payeeName, serviceName, time, cardCode, startaxAmount,
				endtaxAmount, startaxMoney, endtaxMoney);
		return Result.of(list);
	}

	@GetMapping(value = "queryByHistory")
	public Result<PageInfo<SetHistoryVo>> queryByHistory(@RequestParam("page") int page, @RequestParam("rows") int rows,
			@RequestParam("paytaxName") String paytaxName, @RequestParam("starSalesInto") String starSalesInto,
			@RequestParam("endSalesInto") String endSalesInto, @RequestParam("startaxMoney") String startaxMoney,
			@RequestParam("endtaxMoney") String endtaxMoney, @RequestParam("starStarTime") String starStarTime,
			@RequestParam("endStarTime") String endStarTime, @RequestParam("starEndTime") String starEndTime,
			@RequestParam("endEndTime") String endEndTime, @RequestParam("taxNumber") String taxNumber) {
		String json = platformGrantApi.queryByHistory(page, rows, paytaxName, starSalesInto, endSalesInto, startaxMoney,
				endtaxMoney, starStarTime, endStarTime, starEndTime, endEndTime, taxNumber);
		return Result.of(JSON.parseObject(json, PageInfo.class));
	}

	@RequestMapping("/exportem")
	public String exportem(ServletOutputStream outputStream, HttpServletResponse resp, Integer status) {
		// 一.创建工作搏
		XSSFWorkbook workbook = new XSSFWorkbook();
		// 二.创建工作表
		XSSFSheet sheet = workbook.createSheet("导入模板");
		// 设置日期格式
		XSSFCellStyle style = workbook.createCellStyle();
		short fommart = workbook.createDataFormat().getFormat("yyyy年MM月dd日");
		style.setDataFormat(fommart);
		// 三.创建行 ---下标为0
		XSSFRow sheetRow = sheet.createRow(0);
		// 填充表头
		List<String> splitTitles = new ArrayList<>();
		splitTitles.add("纳税人名称");
		splitTitles.add("税号");
		splitTitles.add("税种");
		splitTitles.add("销售收入");
		splitTitles.add("税额");
		splitTitles.add("税款所属开始时间");
		splitTitles.add("税款所属结束时间");
		// Set height of the row
		sheetRow.setHeight((short) 500);
		// Create a new font and alter it.
		XSSFFont font = workbook.createFont();
		// 冻结第一行
		sheet.createFreezePane(0, 1, 0, 1);
		// 处理标题行
		for (int i = 0; i < splitTitles.size(); i++) {
			XSSFCell cell = sheetRow.createCell(i);
			sheetRow.setHeight((short) 500);
			cell.setCellValue(splitTitles.get(i));
			cell.setCellStyle(style);
			if (i < 2) {
				sheet.setColumnWidth(i, 7000);
			} else if (i == 2) {
				sheet.setColumnWidth(i, 5000);
			} else {
				sheet.setColumnWidth(i, 4000);
			}
		}

		String format = new SimpleDateFormat("MM-dd").format(new Date());
		// 响应设置
		// 响应头 编码格式ISO8859-1
		try {
			resp.setHeader("content-disposition",
					"attachment;filename=" + URLEncoder.encode("导入模板", "utf-8") + "-" + format + ".xlsx");

			// 响应内容
			resp.setContentType("application/vnd.ms-excel");

			// 将workbook输出流的方式下载到客户端
			outputStream = resp.getOutputStream();
			workbook.write(outputStream);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// return platformGrantApi.exportem();
		return "成功";

	}

	@PostMapping("/findByTime")
	@Decrypt
	@Encrypt
	public Result<List<OrderDetailVO>> findByTime() {
		List<OrderDetailVO> list = platformGrantApi.findByTime();
		return Result.of(list);
	}

	@PostMapping("/findByQueryTime")
	@Decrypt
	@Encrypt
	public Result<List<PersonalTaxVo>> findByQueryTime() {
		List<PersonalTaxVo> list = platformGrantApi.findByQueryTime();
		return Result.of(list);
	}

	@RequestMapping("/findMoney")
	public Result<List<SellerOrderVo>> findMoney(@RequestParam("sellerName") String sellerName,
			@RequestParam("serviceName") String serviceName, @RequestParam("startDate") String startDate,
			@RequestParam("endDate") String endDate, @RequestParam("orderId") String orderId) {
		List<SellerOrderVo> list = platformGrantApi.findMoney(sellerName, serviceName, startDate, endDate, orderId);
		return Result.of(list);
	}

	/**
	 * 申请记录查询接口
	 * 
	 * @param page
	 * @param rows
	 * @param sellerName
	 * @param serviceName
	 * @param startDate
	 * @param endDate
	 * @param orderId
	 * @return
	 */
	@RequestMapping("/queryApply")
	public Result<PageInfo<SellerOrderVo>> queryApply(@RequestParam("page") int page, @RequestParam("rows") int rows,
			@RequestParam("sellerName") String sellerName, @RequestParam("serviceName") String serviceName,
			@RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate,
			@RequestParam("orderId") String orderId) {
		String json = platformGrantApi.queryApply(page, rows, sellerName, serviceName, startDate, endDate, orderId);
		return Result.of(JSON.parseObject(json, PageInfo.class));
	}

	/**
	 * 企业开票页面查询接口
	 * 
	 * @param page
	 * @param rows
	 * @param sellerName
	 * @param serviceName
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	@RequestMapping("/queryBilling")
	public Result<PageInfo<SellerBillAndConsigneeVo>> queryBilling(@RequestParam("page") int page,
			@RequestParam("rows") int rows, @RequestParam("sellerCompanyName") String sellerCompanyName,
			@RequestParam("status") String status, @RequestParam("startDate") String startDate,
			@RequestParam("endDate") String endDate) {
		String json = platformGrantApi.queryBilling(page, rows, sellerCompanyName, status, startDate, endDate);
		return Result.of(JSON.parseObject(json, PageInfo.class));
	}

	@RequestMapping("/queryPersonInfo")
	public Result<PageInfo<PersonAndAccountVo>> queryPersonInfo(@RequestParam("page") int page,
			@RequestParam("rows") int rows, @RequestParam("personName") String personName,
			@RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate,
			@RequestParam("cardStatus") String cardStatus, @RequestParam("cardCode") String cardCode,
			@RequestParam("iphone") String iphone) {
		String json = platformGrantApi.queryPersonInfo(page, rows, personName, startDate, endDate, cardStatus, cardCode,
				iphone);
		return Result.of(JSON.parseObject(json, PageInfo.class));
	}

	@PostMapping(value = "list/page")
	public Result<PageInfo<SellerOrderVo>> queryGrantList(SellerOrderVo sellerOrderVo) {
		String json = JSON.toJSONString(sellerOrderVo);
		json = platformGrantApi.findListSellerOrder(json);
		return Result.of(JSON.parseObject(json, PageInfo.class));
	}

	@GetMapping(value = "exportGrant")
	public Result<PageInfo<SellerOrderVo>> exportGrant(@RequestParam("sellerName") String sellerName,
			@RequestParam("serviceName") String serviceName, @RequestParam("startDate") String startDate,
			@RequestParam("endDate") String endDate, @RequestParam("orderId") String orderId,
			HttpServletResponse response) {
		try {
			List<SellerOrderVo> list = platformGrantApi.exportGrant(sellerName, serviceName, startDate, endDate,
					orderId);

			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).getOrderType() == 2 && list.get(i).getApproveStatus() == 0) {
					list.get(i).setYongJinView("商户取消");
				} else if (list.get(i).getOrderType() == 2 && list.get(i).getApproveStatus() == 2) {
					list.get(i).setYongJinView("取消发放");
				} else if (list.get(i).getOrderType() == 2 && list.get(i).getApproveStatus() == 4) {
					list.get(i).setYongJinView("取消发放");
				} else if (list.get(i).getOrderType() == 1 && list.get(i).getApproveStatus() == 1) {
					list.get(i).setYongJinView("已完成");
				} else if (list.get(i).getOrderType() == 1 && list.get(i).getApproveStatus() == 8) {
					list.get(i).setYongJinView("已完成");
				} else if (list.get(i).getOrderType() == 0 && list.get(i).getApproveStatus() == 3) {
					list.get(i).setYongJinView("审核中");
				} else if (list.get(i).getOrderType() == 0 && list.get(i).getApproveStatus() == 1) {
					list.get(i).setYongJinView("支付中");
				} else {
					list.get(i).setYongJinView("无");
				}

				if (list.get(i).getFailedAmount() != null) {
					list.get(i).setMoney(list.get(i).getRealAmount().subtract(list.get(i).getFailedAmount()));
				}
			}

			ExcelUtils.exportExcelToTarget(response, FILE_GRENTNAME, list, SellerOrderExcel.class);
			return Result.of(JSON.parseObject("", PageInfo.class));
		} catch (Exception e) {
			log.error("exportGrantList error:{}", e.getMessage(), e);
		}
		return Result.of(JSON.parseObject("", PageInfo.class));
	}

	@GetMapping(value = "export")
	public Result<PageInfo<GrantVo>> exportGrantList(@RequestParam("platformGrantId") String platformGrantId,
			HttpServletResponse response) {
		try {
			List<GrantDetailVo> list = platformGrantApi.queryPlatformGrantExportList(platformGrantId);
			for(int i=0;i<list.size();i++){
				list.get(i).setNumberNo(i+1);
			}
			ExcelUtils.exportExcelToTargets(response, FILE_NAME, list, GrantPersonExcel.class,
					list.get(0).getSellerCompanyName());
			return Result.of(JSON.parseObject("", PageInfo.class));
		} catch (Exception e) {
			log.error("exportGrantList error:{}", e.getMessage(), e);
		}
		return Result.of(JSON.parseObject("", PageInfo.class));
	}

	@GetMapping(value = "list/listInfo")
	public ModelAndView grantListInfo() {
		return new ModelAndView("platform/grant/detailsList", "platformGrantInfo", null);
	}

	@GetMapping(value = "settingup")
	public ModelAndView setup(HttpServletRequest request) {
		String tax = (String) request.getSession().getAttribute("tax");
		if (tax == null || tax.equals("")) {
			tax = "3";
		}
		return new ModelAndView("platform/grant/settingup", "tax", tax);
	}

	@RequestMapping("/settingup")
	public String settingup(@RequestParam("tax") String tax, HttpServletRequest session) {
		session.getSession().setAttribute("tax", tax);
		return "设置成功";
	}

	@PostMapping("/importData")
	public String importData(@RequestParam("excelUploadFile") MultipartFile excelUploadFile) {
		String str = platformGrantApi.importData(excelUploadFile);
		return str;
	}

	@GetMapping(value = "list/detail")
	public String queryGrantDetailList(@RequestParam("platformGrantId") String platformGrantId) {
		String str = platformGrantApi.queryPlatformGrantListInfo(platformGrantId);
		return str;
	}

	@GetMapping(value = "list/queryPayment")
	public String queryGrantDetailStatus(@RequestParam("orderId") String orderId, @RequestParam("type") String type) {
		String str = platformGrantApi.queryGrantDetailPaymentStatus(orderId, type);
		return str;
	}

	@PostMapping("update")
	public String updateGrant(SellerOrderVo sellerOrderVo) {
		String rtnJson = "";
		if (null != sellerOrderVo.getApproveStatus() && StringUtils.isNoneBlank(sellerOrderVo.getOrderId())) {
			try {
				rtnJson = platformGrantApi.updateGrant(JSON.toJSONString(sellerOrderVo));
			} catch (Exception e) {
				log.error("updateGrant error:{}", e.getMessage(), e);
			}
		}
		return rtnJson;
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(String cardCode, String time, double payAmount1, String nottax, String perAmount,
			String serviceId, String sellerId, double tax, String ffMoney, String payeeName, String provideDetailId) {

		String json = platformGrantApi.saveSetup(cardCode, time, payAmount1, nottax, perAmount, serviceId, sellerId,
				tax, ffMoney, payeeName, provideDetailId);
		return json;
	}

	@RequestMapping("/findByProjectInfo")
	public Result<List<SellerOrderVo>> findByProjectInfo(@RequestParam("orderId") String orderId) {
		List<SellerOrderVo> list = platformGrantApi.findByProjectInfo(orderId);
		return Result.of(list);
	}

	@RequestMapping(value = "/downFile")
	public void downFile(HttpServletResponse response, HttpServletRequest request, String fileName) {
		OutputStream out = null;
		FileInputStream fis = null;
		// 文件路径
		File dir = new File(filePath + fileName);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		try {
			out = response.getOutputStream();
			// 设置response的Header 防止文件名乱码
			response.addHeader("Content-Disposition",
					"attachment;filename=" + new String((fileName).getBytes("utf-8"), "ISO-8859-1"));
			response.setContentType("application/octet-stream");
			fis = new FileInputStream(dir);
			int b;
			while ((b = fis.read()) != -1) {
				out.write(b);
			}
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
			log.error("执行 文件下载downFile 方法失败：" + e.getMessage());
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (fis != null) {
						fis.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
